package com.xiaohe.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.Channel;
import com.xiaohe.common.exception.NoStockException;
import com.xiaohe.common.to.mq.OrderTo;
import com.xiaohe.common.to.mq.StockDetailTo;
import com.xiaohe.common.to.mq.StockLockedTo;
import com.xiaohe.common.utils.R;
import com.xiaohe.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.xiaohe.gulimall.ware.entity.WareOrderTaskEntity;
import com.xiaohe.gulimall.ware.entity.vo.SkuHasStockVo;
import com.xiaohe.gulimall.ware.feign.OrderFeignService;
import com.xiaohe.gulimall.ware.service.WareOrderTaskDetailService;
import com.xiaohe.gulimall.ware.service.WareOrderTaskService;
import com.xiaohe.gulimall.ware.vo.OrderItemVo;
import com.xiaohe.gulimall.ware.vo.OrderVo;
import com.xiaohe.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohe.common.utils.PageUtils;
import com.xiaohe.common.utils.Query;

import com.xiaohe.gulimall.ware.dao.WareSkuDao;
import com.xiaohe.gulimall.ware.entity.WareSkuEntity;
import com.xiaohe.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@RabbitListener(queues = "stock.release.stock.queue")
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private WareSkuDao wareSkuDao;

    @Autowired
    private WareOrderTaskService orderTaskService;

    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderFeignService orderFeignService;

    @Autowired
    private WareOrderTaskDetailService taskDetailService;

    public void unLockStock(Long skuId,Long wareId,Integer num,Long taskDetailId){
        wareSkuDao.unLockStock(skuId,wareId,num);
        //更新库存工作单的状态
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setTaskId(taskDetailId);
        wareOrderTaskDetailEntity.setLockStatus(2);
        taskDetailService.updateById(wareOrderTaskDetailEntity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                new QueryWrapper<WareSkuEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            //查询当前sku的总库存量
            Long count = baseMapper.getSkuStock(skuId);
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count == null ? false : count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());

        return collect;
    }

    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        /**
         * 保存库存工作单的详情
         */
        orderTaskService.save(wareOrderTaskEntity);

        //1、找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            skuWareHasStock.setSkuId(skuId);
            //查询这个商品在哪里有库存
            List<Long> wareId = wareSkuDao.ListWareIdHasSkuStock(skuId);
            skuWareHasStock.setWareId(wareId);
            skuWareHasStock.setNum(item.getCount());
            return skuWareHasStock;
        }).collect(Collectors.toList());
        //2、锁定库存
        Boolean allLock = true;
        for (SkuWareHasStock skuWareHasStock : collect) {
            Boolean skuStocked = false;
            Long skuId = skuWareHasStock.getSkuId();
            List<Long> wareIds = skuWareHasStock.getWareId();
            if (wareIds == null && wareIds.size() == 0) {
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                long count = wareSkuDao.lockSkuStock(skuId,wareId,skuWareHasStock.getNum());
                //锁失败了，重试下一个仓库
                if(count == 0){

                }else {
                    //成功
                    skuStocked =true;
                    //TODO 告诉MQ库存锁定成功
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity(null,skuId,null,skuWareHasStock.getNum(),wareOrderTaskEntity.getId(),wareId,1);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setId(wareOrderTaskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, stockDetailTo);
                    //防止回滚找不到数据
                    stockLockedTo.setDetailTo(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockedTo);
                    break;
                }
            }
            if (skuStocked == false){
                //所有仓库都没有锁住
                throw  new NoStockException(skuId);
            }
        }

        //3、肯定都是锁定成功的

        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        Long id = to.getId();//库存工作单的id
        StockDetailTo detailTo = to.getDetailTo();
        Long skuId = detailTo.getSkuId();
        Long detailId = detailTo.getId();
        //查询数据库，关于这个订单的锁定库存信息
        //有
        //没有 库存锁定失败，库存回滚 这种情况无需回滚
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if (byId!=null){
            //解锁
            Long id1 = to.getId();
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id1);
            String orderSn = taskEntity.getOrderSn();//根据订单号查询订单状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if(r.getCode() == 0){
                //成功
                OrderVo orderVo = (OrderVo) r.get(new TypeReference<OrderVo>() {
                });
                if (orderVo == null || orderVo.getStatus() ==4){
                    ////订单不存在 或者 订单被取消了，才能被解锁库存
                    if(byId.getLockStatus()==1){
                        //当前库存工作单详情状态为1 已锁定
                        unLockStock(detailTo.getSkuId(),detailTo.getWareId(),detailTo.getSkuNum(),detailId);
                    }

                }
            }else {
                //消息拒绝以后重新放入到队列里面，让别人来消费解锁
                throw new RuntimeException("远程调用服务失败");
            }
        }else {
            //无需解锁
        }
    }

    //放在订单服务卡顿，导致订单状态一直改不了，库存消息优先到期，
    @Override
    @Transactional
    public void unlockStock(OrderTo order) {
        String orderSn = order.getOrderSn();
        //查一下最新的库存的状态
        WareOrderTaskEntity task = orderTaskService.getOrdertaskByOrderSn(orderSn);
        Long id = task.getId();
        //按照工作单，找到所有没有解锁的库存
        QueryWrapper<WareOrderTaskDetailEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_id",id);
        queryWrapper.eq("lock_status",1);
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(queryWrapper);
        for (WareOrderTaskDetailEntity entity : list) {
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }
    }

    @Data
   static class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }
}